package androidapp.firstapp;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.SlidingDrawer;
import android.widget.Toast;

public class MainActivity extends Activity {
	 public final static String EXTRA_MESSAGE = "androidapp.firstapp.MESSAGE";
	 private static int RESULT_LOAD_IMAGE = 1;
	 public static final int FIRST_ELEMENT = 1;
	 public static final int SECOND_ELEMENT = 2;
	 static final int REQUEST_IMAGE_CAPTURE = 88;
	 private static final int CAPTURE_IMAGE_ACTIVITY = 44;
	 static final int REQUEST_TAKE_PHOTO = 77;
	 int chunkNumbers = 0;
	 String filepath="";
	 ImageView imageView;
	 boolean imgSelected = false;
	 File _file;
	 File _dir;
	 String mCurrentPhotoPath;
	 SlidingDrawer slidingDrawer;
	 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        slidingDrawer = (SlidingDrawer) findViewById(R.id.split_slider);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	//getMenuInflater().inflate(R.menu.menu, menu);
        // Inflate the menu; this adds items to the action bar if it is present.
    	 menu.add(0, FIRST_ELEMENT, 0, "Clear");
    	 menu.add(1, SECOND_ELEMENT, 0, "Exit Game");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
    	//String ktoryElement = "";
    	 
        switch (item.getItemId()) {
     
        case FIRST_ELEMENT:
            //ktoryElement = "Clear";
            ImageView imageView = (ImageView) findViewById(R.id.imageView1);
        	imageView.setImageBitmap(BitmapFactory.decodeFile(""));
        	//Button startButton = (Button) findViewById(R.id.start_button);
        	filepath= "";
            //startButton.setClickable(false);
        	 this.imgSelected = false;
            break;
        case SECOND_ELEMENT:
            //ktoryElement = "second";
            finish();
            break;
        default:
           // ktoryElement = "none";
     
        }
     
        //Toast.makeText(getApplicationContext(), "Element: " + ktoryElement, Toast.LENGTH_LONG).show();
   
     
        return true;

    }
    
    
    
    public void browseGallery(View view) {
        // Do something in response to button
    	 Intent i = new Intent(
                 Intent.ACTION_PICK,
                 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
          
         startActivityForResult(i, RESULT_LOAD_IMAGE);
    }
    
    public void setThree(View view) {
        // Do something in response to button
    	slidingDrawer.animateClose();
    	chunkNumbers = 9 ; 
    	if (!imgSelected) {
    		Toast.makeText(getApplicationContext(), "First choose or take a pic!", Toast.LENGTH_SHORT).show();
    	//	slidingDrawer.animateClose();
    		return;
    	}
    	Intent intent = new Intent(this, Nine_puzzles.class);
		intent.putExtra(EXTRA_MESSAGE, filepath);
		intent.putExtra("Chunks", chunkNumbers);
		startActivity(intent);
    }
    
    public void setFour(View view) {
        // Do something in response to button
    	slidingDrawer.animateClose();
    	if (!imgSelected) {
    		Toast.makeText(getApplicationContext(), "First choose or take a pic!", Toast.LENGTH_SHORT).show();
    		//slidingDrawer.animateClose();
    		return;
    	}
    	chunkNumbers = 16 ; 
    	Intent intent = new Intent(this, FourPuzzles.class);
		intent.putExtra(EXTRA_MESSAGE, filepath);
		intent.putExtra("Chunks", chunkNumbers);
		startActivity(intent);
    }
    
    public void setFive(View view) {
        // Do something in response to button
    	slidingDrawer.animateClose();
    	if (!imgSelected) {
    		Toast.makeText(getApplicationContext(), "First choose or take a pic!", Toast.LENGTH_SHORT).show();
    		//slidingDrawer.animateClose();
    		return;
    	}
    	chunkNumbers = 25 ; 
    	Intent intent = new Intent(this, FivePuzzles.class);
		intent.putExtra(EXTRA_MESSAGE, filepath);
		intent.putExtra("Chunks", chunkNumbers);
		startActivity(intent);
    }
    
    
    public void takePhoto(){
    	String path = Environment.getExternalStorageDirectory() + "/photo1.jpg";

        File file = new File(path);
        Uri outputFileUri = Uri.fromFile(file);
        Intent intent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(_file));
        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY);
    	
    }
    
    @SuppressLint("SimpleDateFormat")
	private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
    
    public void takePhoto(View view) {

    	dispatchTakePictureIntent();
	
    }
    
    public void setPicture(String filePath){
    	
    	//Toast.makeText(getApplicationContext(), "Element: " + filePath, Toast.LENGTH_LONG).show();
        Log.d("PK", "File: " + filePath);
        BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize=Nine_puzzles.calculateInSampleSize(options, 750,1350);
        options.inJustDecodeBounds = false;
        
        imageView = (ImageView) findViewById(R.id.imageView1);
        imageView.setImageBitmap(BitmapFactory.decodeFile(filePath, options)); 
        this.imgSelected = true;
    	
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
 
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            filepath = picturePath;
            setPicture(filepath);
            
                     
        }
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

        	//Toast.makeText(getApplicationContext(), "File saved in " + mCurrentPhotoPath, Toast.LENGTH_SHORT).show();
        	filepath = mCurrentPhotoPath;
        	galleryAddPic();
        	setPicture(filepath);
                          
        }
        

    }
    
    
    
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
              
            
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();Log.d("PK", "URI" +  Uri.fromFile(photoFile).toString());
            } catch (IOException ex) {
                // Error occurred while creating the File
            	Log.d("PK", "Cant Create file");
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                Log.d("PK", Uri.fromFile(photoFile).toString());
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
  
                                
            }
        }
    }


	 
	 private void galleryAddPic() {
		    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		    File f = new File(mCurrentPhotoPath);
		    Uri contentUri = Uri.fromFile(f);
		    mediaScanIntent.setData(contentUri);
		    this.sendBroadcast(mediaScanIntent);
		}
}
